<!--选择交易对-多币对-->
<template>
  <div class="bg bg1" @viewappear="viewappear" @viewdisappear="viewdisappear" @rightBtn="okClick">
    <div class="bg bg1" v-if="searchpairs">
      
      <!--搜索栏-->
      <div class="search bg2">
        <div class="search-content bg1">
          <LImage class="search-image" :src="Config.img('sousuo.png')"></LImage>
          <input class="search-input font28 text1"
                :ref="'input'"
                :placeholder="T('搜索交易对')"
                v-model="searchKey"
                type="text"
                @return="searchClick">

          <div class="search-but" @click="searchClick">
            <text class="font24 main-t1">{{T('搜索')}}</text>
          </div>
        </div>
      </div>

      <!--排序-->
      <div class="sort">

        <div class="left value" @click="sortClick(0, 0)">
          <text class="font24 text2">{{T('币种')}}</text>
        </div>

        <div class="width20"></div>
        <div class="acenter value" @click="sortClick(1, ((sortDire == 0 || sortDire == 2) ? 1 : 2))">
          <text class="font24 text2">{{T('价格')}}</text>
          <div class="sort-arrow">
            <text :class="['font12', 'sort-arrow-text', (sortType == 1 && sortDire == 1 ? 'text1' : 'text2')]">▲</text>
            <text :class="['font12', 'sort-arrow-text', (sortType == 1 && sortDire == 2 ? 'text1' : 'text2')]">▼</text>
          </div>
        </div>

        <div class="width20"></div>
        <div class="right value" @click="sortClick(2, ((sortDire == 0 || sortDire == 2) ? 1 : 2))">
          <text class="font24 text2">{{T('涨跌幅')}}</text>
          <div class="sort-arrow">
            <text :class="['font12', 'sort-arrow-text', (sortType == 2 && sortDire == 1 ? 'text1' : 'text2')]">▲</text>
            <text :class="['font12', 'sort-arrow-text', (sortType == 2 && sortDire == 2 ? 'text1' : 'text2')]">▼</text>
          </div>
        </div>
        <div class="image"></div>
      </div>

      <!--列表-->
      <div class="all">
        <VTips text="无结果" v-if="isTips"></VTips>
        <list class="list">

          <cell v-for="(item, index) in searchpairs" v-bind:key="index">
            
            <div :class="['cell', item.select ? 'bg3' : '']" @click="cellClick(item)">
              <div class="left value">
                <text class="font32 text1">{{item.counterCoin}}</text>
                <text class="font24 text2">{{'/'+item.baseCoin}}</text>
              </div>

              <div class="width20"></div>
              <div class="acenter value">
                <text class="font32 text1">{{Config.toNonNum(item.last)}}</text>
              </div>

              <div class="width20"></div>
              <div class="right value">
                <text :class="['font32', Config.upDownFont(item.increase)]">{{item.increase+'%'}}</text>
              </div>

              <LImage class="image" :src="Config.img(item.select ? 'xuanzhong.png' : 'weixuan.png')"></LImage>
            </div>
          </cell>
        </list>
      </div>
    </div>
  </div>
</template>

<script>
//组件
import VTips from "@/public/view/VTips";

//功能
import navigator from "@/_js/navigator";
import modal from "@/_js/modal";
import math from "@/_js/math";
import Config from "@/_js/config";

import sort from "@/_js/sort";
import broadcast from "@/_js/broadcast";

const weexFunction = weex.requireModule("WeexFunction");
import weexHttp from "@/_js/https"; ;
const WeexMqtt = weex.requireModule("WeexMqtt");

import I18N from "@/_i18n/i18n";
var T = I18N.t;
weexFunction.setTitle(T('选择交易对'));
weexFunction.setRightBtn(T('确认'));

export default {
  
  components: {
    VTips,
  },

  data() {
    return {
      T: T,
      math:math,
      Config:Config,

      exchangeName:'', //交易所名称
      exchangeId:'', //交易所ID
      target: false, //true 赚交易币， false 赚本币
      counterCoin:'',
      baseCoin:'',
    
      pairMaps:[], //默认选中币对
      datas: [], //未排序数据

      isTips:false, //turn显示空提示
      searchKey:'', //搜索关键字
      searchpairs: [], //筛选后数据

      sortType: 0, // 0默认排序 1价格排序 2涨跌幅排序
      sortDire: 0, // 1向上  2向下
      sortPairs:[], //排序后数据


      mqtts:{}, //Mqtt订阅返回消息
      timeHandler: undefined, //自动更新定时
    };
  },

  mounted() {

    this.timeRefreshList();

    //MQTT消息回调
    WeexMqtt.message((data)=>{
      
      var array = data.topic.split('/');
      var baseCoin = array[4];
      var counterCoin = array[5];
      
      var messages = JSON.parse(data.message);
      var last = messages[0];
      var increase = messages[2];

      var key = baseCoin + counterCoin;
      this.mqtts[key] = {'last':last, 'increase':increase};
    });
    
    Config.init(()=>{

      this.exchangeName = navigator.getParam('exchangeName');
      this.exchangeId = navigator.getParam('exchangeId');
      this.pairMaps = navigator.getParam('pairMaps');

      this.target = navigator.getParam('target');
      this.counterCoin = navigator.getParam('counterCoin');
      this.baseCoin = navigator.getParam('baseCoin');

      this.httpPairs();
    },[Config.OPT_UP_DOWN]);
  },

  methods: {

    //初始化数据
    initData(data) {

      //首字母排序
      var datas = data.sort((a, b) => {
        var coin1 = a.counterCoin.slice(0,1);
        var coin2 = b.counterCoin.slice(0,1);
        return coin1.localeCompare(coin2);
      })

      //价格处理
      var pairs = [];
      for (let index = 0; index < datas.length; index++) {
        var pair = datas[index];
        pair.last = math.xiaoShuDelete0(pair.last);
        pair.increase = math.xiaoShuDelete0(pair.increase);
        if (pair.counterCoin != this.counterCoin || pair.baseCoin != this.baseCoin) {
          pairs.push(pair);
        }
        
        //检查选中
        pair.select = false;
        for (let index = 0; index < this.pairMaps.length; index++) {
          var map = this.pairMaps[index];
          if (pair.counterCoin == map.counterCoin && pair.baseCoin == map.baseCoin) {
            pair.select = true;
            break;
          }
        }
      }
      return pairs;
    },

    /*************************************************通信触发*/
    //完全显示
    viewappear() {
    },

    //完全隐藏
    viewdisappear() {
      if(this.timeHandler){
        clearTimeout(this.timeHandler);
      }
      WeexMqtt.unSubscribes();
      WeexMqtt.message(null);
    },
    
    /*************************************************HTTP*/
    //http可选交易对
    httpPairs() {
      
      modal.showLoad();
      var param = {'exchangeId':this.exchangeId};
      
      if (this.target) {
        param['counterCoin'] = this.counterCoin;
      } else {
        param['baseCoin'] = this.baseCoin;
      }
      weexHttp.post("quoteV3/queryPairByCoin",param,true,(data)=>{

        modal.hideLoad();
        if(data.status == 200){
          data = data.data;
          this.datas = this.initData(data);
          this.sortClick(this.sortType, this.sortDire);
          this.subscribes();
        } else {
          modal.toast(data.msg);
        }
      });
    },
    
    /********************************** 其他方法*/
    //1秒刷新一次列表
    timeRefreshList(){
      
      if(this.timeHandler){
        clearTimeout(this.timeHandler);
      }

      this.timeHandler = setTimeout(() => {

        var mqtts = JSON.parse(JSON.stringify(this.mqtts));
        this.mqtts = {};

        var pairs = JSON.parse(JSON.stringify(this.datas));
        for (let index = 0; index < pairs.length; index++) {
          var pair = pairs[index];
          var baseCoin = pair.baseCoin.toUpperCase();
          var counterCoin = pair.counterCoin.toUpperCase();
          var key = baseCoin + counterCoin;
          if (mqtts[key]) {
            var mqtt = mqtts[key]
            pair.last = math.xiaoShuDelete0(mqtt.last);
            pair.increase = math.xiaoshu(mqtt.increase, 2, 2);
          }
        }
        this.datas = pairs;
        this.sortClick(this.sortType, this.sortDire);
        this.timeRefreshList();
      }, 1000);
    },

    //订阅主题
    subscribes(){

      WeexMqtt.unSubscribes();
      var exchangeName = this.exchangeName.toUpperCase();
      var topics = [];
      for (let index = 0; index < this.datas.length; index++) {
        var pair = this.datas[index];
        var baseCoin = pair.baseCoin.toUpperCase();
        var counterCoin = pair.counterCoin.toUpperCase();
        var topic = 'public/market/spot/' + exchangeName + '/' + baseCoin + '/' + counterCoin;
        topics.push(topic);
      }
      WeexMqtt.subscribes(topics);
    },

    /********************************** 点击触发*/
    //右按钮触发
    okClick() {

      var pairs = [];
      for (let index = 0; index < this.datas.length; index++) {
        var pair = this.datas[index];
        if (pair.select) {
          pairs.push(pair);
        }
      }
      broadcast.send('SelectPairMany', pairs);
      navigator.back();
    },

    //搜索
    searchClick() {

      if(this.searchKey.length == 0) {
        this.isTips = !this.sortPairs.length;
        this.$nextTick(()=>{
          this.searchpairs = this.sortPairs;
        })
        return;
      }

      var searchpairs = [];
      for (let index = 0; index < this.sortPairs.length; index++) {

        var pair = this.sortPairs[index];
        var searchKey = this.searchKey.toLowerCase();
        var counterCoin = pair.counterCoin.toLowerCase();
        if (counterCoin.indexOf(searchKey) >= 0) {
          searchpairs.push(pair);
        }
      }
      this.isTips = !searchpairs.length;
      this.$nextTick(()=>{
        this.searchpairs = searchpairs;
      });
    },

    //排序点击
    /** 排序
     * type: 0默认排序 1价格排序 2涨跌幅排序
     * dire: 1向上  2向下
     */
    sortClick(type, dire){
      this.sortType = type;
      this.sortDire = dire;

      if (type == 0) {

        this.sortPairs = this.datas.sort((a, b) => {
          var coin1 = a.counterCoin.slice(0,1);
          var coin2 = b.counterCoin.slice(0,1);
          return coin1.localeCompare(coin2);
        })
      } else if (type == 1) {
        this.sortPairs = sort.maoPao(this.datas, 'last', dire);
      } else if (type == 2) {
        this.sortPairs = sort.maoPao(this.datas, 'increase', dire);
      }
      this.searchClick();
    },

    //cell点击
    cellClick(item) {
      if (item.select) {
        item.select = false;
        return;
      }

      var num = 0;
      for (let index = 0; index < this.datas.length; index++) {
        var pair = this.datas[index];
        if (pair.select) {
          num = num + 1;
        }
      }

      if (num >= 19) {
        modal.toast(T('最多选择20个交易对'))
        return;
      }
      item.select = true;
    },
  },
};
</script>


<style src="@/_css/style.css"></style>
<style scoped>
.bg {
  width: 750px;
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}
.scroller {
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 9;
}
.wrapper{
  height: 80px;
  flex-direction: row;
}

/***********************************搜索*/
.search {
  flex-direction: row;
  align-items: center;
  width: 750px;
  height: 104px;
  padding-left: 40px;
  padding-right: 40px;
}
.search-content {
  flex-direction: row;
  align-items: center;
  width: 670px;
  height: 60px;
  border-radius: 4px;
}
.search-image {
  width: 24px;
  height: 24px;
  margin-left: 20px;
  margin-right: 20px;
}
.search-input{
  flex: 1;
  height: 88px;
  placeholder-color:#6E7488;
}
.search-but {
  flex-direction: row;
  align-items: center;
  justify-content: center;
  height: 104px;
  padding-left: 20px;
  padding-right: 20px;
}

/*********************************** 排序*/
.sort {
  flex-direction: row;
  align-items: center;
  width: 750px;
  height: 70px;
  padding-left: 40px;
  padding-right: 40px;
}
.sort-line{
  position: absolute;
  width: 750px;
  height: 1px;
  margin-left: -40px;
  bottom: 0;
}
.sort-arrow{
  margin-left: 8px;
  flex-direction: column;
}
.sort-arrow-text{
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 100;
  height: 14px;
  line-height: 14px;
}
.sort-height4{
  height: 4px;
}

/*********************************** 通用*/
.left{
  flex: 8;
}
.center{
  flex: 7;
}
.right{
  flex: 5;
  justify-content: flex-end;
}
.width20{
  width: 20px;
}

/*********************************** 列表*/
.list {
  width: 750px;
  flex: 1;
}
.cell {
  flex-direction: row;
  align-items: center;
  width: 750px;
  height: 80px;
  padding-left: 40px;
  padding-right: 40px;
}
.value{
  height: 70px;
  flex-direction: row;
  align-items: center;
}
.image {
  width: 29px;
  height: 29px;
  margin-left: 52px;
}
</style>
